import 'dart:math';

import 'package:flutter/material.dart';
import 'package:fl_chart/fl_chart.dart';

class LineMaxDataChart extends StatefulWidget {
  const LineMaxDataChart({super.key});

  @override
  _LineMaxDataChartState createState() => _LineMaxDataChartState();
}

class _LineMaxDataChartState extends State<LineMaxDataChart> {
  final int totalDataPoints = 10000000;
  final int visiblePoints = 900;
  final ScrollController _scrollController = ScrollController();
  List<FlSpot> _currentSpots = [];
  List<FlSpot> allSpot = [];

  //一个点占用多少个像素
  late double _pixelPerPoint;

  @override
  void initState() {
    super.initState();

    WidgetsBinding.instance.addPostFrameCallback((_) {
      _initializeChart();
      _scrollController.addListener(_handleScroll);
    });
  }

  void _initializeChart() {
    final random = Random();
    allSpot = List.generate(totalDataPoints, (index) {
      //价格随机生成
      final price = random.nextInt(95).toDouble() + 1;
      return FlSpot(index.toDouble(), price);
    }).toList();

    final screenWidth = MediaQuery.of(context).size.width;
    _pixelPerPoint = screenWidth / visiblePoints;
    final initialOffset = 0.0;
    _scrollController.jumpTo(initialOffset);
    _updateVisibleData(initialOffset);
  }

  void _handleScroll() {
    _updateVisibleData(_scrollController.offset);
  }

  void _updateVisibleData(double scrollOffset) {
    final startIndex = (scrollOffset / _pixelPerPoint).floor();
    final endIndex = startIndex + visiblePoints;
    // print("当前位置 ${scrollOffset}  startIndex = ${startIndex},,endIndex=${endIndex}");
    setState(() {
      _currentSpots = allSpot.sublist(startIndex, endIndex);
      // print("_currentSpots = ${_currentSpots}");
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('10万数据流畅滚动图表')),
      body: SizedBox(
        height: 300,
        child: Stack(
          children: [
            // 图表可视化层
            Positioned.fill(
              child: LineChart(
                LineChartData(
                  lineBarsData: [_buildLineData()],
                  // gridData: FlGridData(show: false),
                  titlesData: FlTitlesData(
                    show: true,
                  ),
                  // borderData: FlBorderData(show: false),
                  // minX: _currentSpots.isNotEmpty ? _currentSpots.first.x : 0,
                  // maxX: _currentSpots.isNotEmpty ? _currentSpots.last.x : 0,
                  lineTouchData: LineTouchData(enabled: false),
                ),
                duration: Duration.zero,
              ),
            ),

            // 滚动控制层
            Positioned.fill(
              child: SingleChildScrollView(
                controller: _scrollController,
                scrollDirection: Axis.horizontal,
                physics: const BouncingScrollPhysics(),
                child: SizedBox(
                  width: totalDataPoints * _pixelPerPoint,
                  height: 1, // 隐藏滚动条
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  LineChartBarData _buildLineData() {
    return LineChartBarData(
      spots: _currentSpots,
      isCurved: false,
      curveSmoothness: 0.3,
      // colors: [Colors.blueAccent],
      barWidth: 1.5,
      isStrokeCapRound: true,
      dotData: FlDotData(show: false),
      belowBarData: BarAreaData(show: false),
    );
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }
}
